<?php
namespace app\index\controller;
use think\Controller;
use think\view;
use think\Db;
use think\Session;
use think\Request;
class Wx extends Controller {

    function show($status,$message,$data=array()){
        $reuslt = array(
            'status'=>$status,
            'message'=>$message,
            'data'=>$data,
        );
        exit(json_encode($reuslt)) ;   //输出一条信息 并退出当前脚本
    }

    /**
     * 短信发送
     */
    public function msg(){
        if($_POST){
            $phone  = $_POST['phone'];
            $code  =rand(1000,9999);
            $msg= '【宏鑫营客通】您的注册验证码是 '. $code .'，请勿泄露给他人！';
            $res = 	$this->SendSms_Demo_Curl($phone,$msg,"");

            if($res)
            {
                //将手机号和验证码存储
                $data['phone'] =$phone;
                $data['code'] = $code;
                $data['uptime'] = date('Y-m-d H:i:s',time());
                Db::name('phone')->insert($data);
                $this->show(1,'发送成功');
            }else{
                $this->show(0,'发送失败');
            }

        }
    }

    /**
     * 发送短信接口
     */
    function SendSms_Demo_Curl($mobile,$Msg,$longnum){
        $post_data = array();
        $post_data['username'] = "AYHT-1282-007B-F80C";
        $post_data['password'] = "7BF80CAD9E754A8B";
        $post_data['longnum'] = 9082;
        $post_data['phonelist'] = $mobile;
        $post_data['msg'] = $Msg;
        $url='http://api.aoyihutong.com:8180/ayht-interface/SendSms';
        $o="";
        foreach ($post_data as $k=>$v)
        {
            $o.= "$k=".urlencode($v)."&";
        }
        $post_data=substr($o,0,-1);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//不直接输出，返回到变量
        //为了支持cookie
        curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $result = curl_exec($ch);
        curl_close($ch);//关闭

        if((int)strip_tags($result)>0){
            return strip_tags(substr($result,0,strrpos($result,'|')));   //返回发送短信成功数
        }else{
            return false;
        }
    }

     /**
      * 登录接口
      */
     public function login(){


         $password  =$_POST['password'];

         $map['phone']  = $_POST['phone'];

         $ret = Db::name('user')->where($map)->find();
         if(!$ret){
             return $this->show(0,'该用户不存在');
         }

         if(($ret['password'])!=(md5($password))){
             return  $this->show(0,'密码错误');
         }


         $ret['password'] = '';
         $this->show(1,'登录成功',$ret);


     }

    /**
     * 客户注册接口
     */
    public function reg(){

            $phone = $_POST['phone'];
            $msgCode  =$_POST['msgCode'];
            $msg  = Db::name('phone')->where(array(
                'phone'=>$phone,
                'code'=>$msgCode
            ))
                ->find();

            if(!$msg){
                $this->show(0,'验证码错误');
            }

            $user  =Db::name('user')->where(array(
                'phone'=>$phone
            ))->find();
            if($user){
                $this->show(0,'该手机号已注册，请更换手机号');
            }


            $_POST['uptime'] = date('Y-m-d H:i:s',time());
            $_POST['token'] = time();
            $_POST['password'] = md5( $_POST['password']);
            $_POST['state'] = 1;  //刚注册的状态

            $add = Db::name('user')->insert($_POST);
            if($add){
                $this->show(1,'注册成功，请登录',$_POST['token']);
            }else{
                $this->show(0,'注册失败，请重试');
            }




    }
    /**
     * 修改个人信息接口
     */
    public function edit(){
        $header = Request::instance()->header();
        $token  = $header['token'];
        $user = DB::name('user')
            ->field('id')
            ->where(array(
            'token'=>$token
        ))->find();

        $_POST['uptime'] = date('Y-m-d H:i:s',time());
       $res  = Db::name('user')->where(array(
            'id'=>$user['id']
        ))->update($_POST);
        if($res){
            $this->show(1,'修改成功');
        }else{
            $this->show(0,'修改失败');
        }
    }


    /**
     * 请求用户信息接口
     */
    public function get_user(){

            $header = Request::instance()->header();
            $token  = $header['token'];

             $res  = Db::name('user')->where(array(
                 'token'=>$token,

             ))
                 ->find();
             $res['password'] = '';
             if($res){
                 $this->show(1,'获取成功',$res);
             }else{
                 $this->show(0,'获取失败');
             }
         }

    /**
     * 获取全部标签
     */

    public function get_tags()
    {

        $header = Request::instance()->header();
        $token = $header['token'];

        $user = Db::name('user')->where(array(
            'token' => $token,
        ))
            ->find();
        if(!$user){
            $this->show(0, '无访问权限，请注册系统');
        }
        $res = Db::name('tag_detail')

            ->select();



        if ($res) {
            $this->show(1, '获取成功', $res);
        } else {
            $this->show(1, '暂无数据');
        }
    }

    /**
     * 主页列表
     */
    public function get_list(){
        if (trim($_GET['limit'])) {
            $limit = trim($_GET['limit']);
        }else{
            $limit = 15;
        }
        $pageSize = $limit;
        $page = $_GET['page'];
        $tag = $_GET['tag'];



        $header = Request::instance()->header();
        $token = $header['token'];

        $user = Db::name('user')->where(array(
            'token' => $token,
        ))
            ->find();
        if(!$user){
            $this->show(0, '无访问权限，请注册系统');
        }

        $sql = DB::name('list');
        if($tag){
            $list = $sql
                ->whereOr('tag', 'like', '%' . $tag . '%')
                ->order('uptime desc')
                ->page($page,$pageSize)
                ->select();
            $count = $sql
                ->whereOr('tag', 'like', '%' . $tag . '%')
                ->count();
        }
        if(!$tag){
            $list = $sql
                ->order('uptime desc')
                ->page($page,$pageSize)
                ->select();
            $count = $sql
                ->count();
        }

        //计算喜欢数
        for($i=0;$i<count($list);$i++){
            $love = db::name('love')

                ->where(array(
                    'list_id'=>$list[$i]['id']
                ))->count();
            $list[$i]['love'] = $love;

        }

        if($list){
            $data['code'] = '0';
            $data['msg'] = '获取成功';
            $data['count'] = $count;
            $data['data'] = $list;
        }else{
            $data['code'] = '0';
            $data['msg'] = '暂无数据';
            $data['count'] = 0;
            $data['data'] = '';
        }

        exit(json_encode($data));


    }
    /**
     * 列表详情
     */
    public function get_detail(){
        $header = Request::instance()->header();
        $token = $header['token'];

        $user = Db::name('user')->where(array(
            'token' => $token,
        ))
            ->find();
        if(!$user){
            $this->show(0, '无访问权限，请注册系统');
        }
        if($_GET){
            $map['id']  = $_GET['id'];
            $list = Db::name('list')->where($map)->find();
//            增加浏览数量
            Db::name('list')->where(
                array(
                    'id'=>$map['id']
                )
            )->setInc('see');
//            显示附件
            $file = DB::name('file')
                ->where(array(
                    'anli_id'=>$list['id']
                ))->select();
            $list['file'] = $file;
//           计算喜欢数
            $love = db::name('love')

                ->where(array(
                    'list_id'=>$list['id']
                ))->count();
            $list['love'] = $love;
//            判断当前用户是否喜欢
            $love_yes = db::name('love')
                ->where
                (array(
                    'list_id'=>$list['id'],
                    'user_id'=>$user['id']
                ))
                ->find();

            $list['yes'] = $love_yes['love'];

            if ($list) {
                $this->show(1, '获取成功', $list);
            } else {
                $this->show(1, '暂无数据');
            }
        }


    }
    /**
     * 同类案例
     */
    public function get_like(){
        $header = Request::instance()->header();
        $token = $header['token'];

        $user = Db::name('user')->where(array(
            'token' => $token,
        ))
            ->find();
        if(!$user){
            $this->show(0, '无访问权限，请注册系统');
        }

        $sql = DB::name('list');

        $key_word = $_POST['key_word'];
        if($key_word) {
            $list = $sql
                ->whereOr('tag', 'like', '%' . $key_word . '%')
                ->order('uptime desc')
                ->limit(5)
                ->select();
            $count = $sql
                ->whereOr('tag', 'like', '%' . $key_word . '%')
                ->count();
        }


        if($list){
            $data['code'] = '0';
            $data['msg'] = '获取成功';
            $data['count'] = $count;
            $data['data'] = $list;
        }else{
            $data['code'] = '0';
            $data['msg'] = '暂无数据';
            $data['count'] = 0;
            $data['data'] = '';
        }

        exit(json_encode($data));

        
    }
    /**
     *  喜欢 取消喜欢
     */
    public function love(){
        $header = Request::instance()->header();
        $token = $header['token'];

        $user = Db::name('user')->where(array(
            'token' => $token,
        ))
            ->find();
        if(!$user){
            $this->show(0, '无访问权限，请注册系统');
        }


        $db = DB::name('love');
//        先判断是否有该条数据
        $map['user_id'] = $user['id'];
        $map['list_id'] = $_POST['list_id'];


        $res = $db
            ->where($map)
            ->field('love')
            ->find();
        if($res){
            if($res['love'] == 1){
                $data['love'] = 0;
                $data['user_id'] = $user['id'];
                $data['list_id'] = $_POST['list_id'];
                $data['uptime'] = date('Y-m-d H:i:s',time());
                $res = $db->where($map)->update($data);
                if($res){
                    return show(1,'取消喜欢成功',$data['love']);
                }else{
                    return show(0,'已设置，请勿重复设置');
                }
            }
            if($res['love'] == 0){
                $data['love'] = 1;
                $data['user_id'] = $user['id'];
                $data['list_id'] = $_POST['list_id'];
                $data['uptime'] = date('Y-m-d H:i:s',time());
                $res = $db->where($map)->update($data);
                if($res){
                    return show(1,'喜欢成功',$data['love']);
                }else{
                    return show(0,'已设置，请勿重复设置');
                }
            }


        }else{
//            写入该条数据
            $data['user_id'] = $user['id'];
            $data['list_id'] = $_POST['list_id'];
            $data['love'] = 1;
            $data['uptime'] = date('Y-m-d H:i:s',time());
            $res = $db->insert($data);

            if($res){
                return show(1,'喜欢成功',$data['love']);
            }else{
                return show(0,'已设置，请勿重复设置');
            }
        }


    }
    /**
     * 我的喜欢列表
     */
    public function my_love(){
        $header = Request::instance()->header();
        $token = $header['token'];

        $user = Db::name('user')->where(array(
            'token' => $token,
        ))
            ->find();
        if(!$user){
            $this->show(0, '无访问权限，请注册系统');
        }

        $list = Db::name('list')
            ->alias('a')
            ->join('love b', 'a.id = b.list_id')
            ->field('a.id,a.title,a.tag,a.img,a.content,a.uptime,a.see')
            ->order('a.uptime desc')
            ->where(array(
                'b.user_id' => $user['id'],
                'b.love'=>1
            ))
            ->select();
        if ($list) {
            $this->show(1, '获取成功', $list);
        } else {
            $this->show(1, '暂无数据');
        }



    }

    /**
     * 删除喜欢
     */
    public function del_like(){
        $header = Request::instance()->header();
        $token = $header['token'];

        $user = Db::name('user')->where(array(
            'token' => $token,
        ))
            ->find();
        if(!$user){
            $this->show(0, '无访问权限，请注册系统');
        }

        $map['user_id'] = $user['id'];
        $map['list_id'] = $_POST['list_id'];

        $res = Db::name('love')->where($map)->delete();
        if($res){
            return show(1,'删除成功');
        }else{
            return show(0,'删除失败，请重试');
        }

    }



      /**
       * 文件上传函数
       */
        public function upload(){
            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('myFile');
//            var_dump($file);

            // 移动到框架应用根目录/public/uploads/ 目录下
            if($file){
                $info = $file->validate(['size'=>12697600,'ext'=>'jpg,png,gif,jpeg,doc,docx,ppt,pptx,xls,xlsx,pdf,txt,mp4,avi,mov,zip,rar,7z'])->move(ROOT_PATH . 'public' . DS . 'uploads');
                if($info){
                    // 成功上传后 获取上传信息

                    $res['path'] = 'https://ck.51tuanke.com/bang/public/uploads/'.$info->getSaveName();
                    $res['name'] = $info->getFilename();
                    $data['name'] =  $res['name'];
                    $data['path'] =   $res['path'];
                    $data['uptime'] = date('Y-m-d H:i:s',time());
                    $add = Db::name('file')->insert($data);
                    $res['id'] = Db::name('order')->getLastInsID();
                    $this->show(1,'获取成功',$res);

                }else{
                    // 上传失败获取错误信息
                    $this->show(0,'获取失败',$file->getError());
                }
            }
        }



}